package cn.scw.project.goods.service.impl;

import cn.scw.common.constant.DictTypeConsts;
import cn.scw.common.constant.GComConsts;
import cn.scw.common.exception.CustomException;
import cn.scw.common.utils.SecurityUtils;
import cn.scw.common.utils.bean.ToolUtils;
import cn.scw.common.utils.sql.JpaUtil;
import cn.scw.project.goods.domain.GCommodity;
import cn.scw.project.goods.domain.GCommodityModel;
import cn.scw.project.goods.domain.netework.bean.GCommodityAddReq;
import cn.scw.project.goods.domain.netework.bean.GCommodityListReq;
import cn.scw.project.goods.domain.netework.bean.GCommodityModelAddReq;
import cn.scw.project.goods.domain.vo.GCommodityVo;
import cn.scw.project.goods.mapper.GCommodityMapper;
import cn.scw.project.goods.service.IGCommodityModelService;
import cn.scw.project.goods.service.IGCommodityService;
import cn.scw.project.goods.service.IGCommodityTypeService;
import cn.scw.project.system.domain.SysUser;
import cn.scw.project.system.service.ISysDictDataService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品Service业务层处理
 *
 * @author api
 * @date 2020-05-20
 */
@Service
public class GCommodityServiceImpl implements IGCommodityService {
    @Autowired
    private GCommodityMapper gCommodityMapper;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private IGCommodityModelService gCommodityModelService;
    @Autowired
    private IGCommodityTypeService gCommodityTypeService;

    /**
     * 查询商品
     *
     * @param id 商品ID
     * @return 商品
     */
    @Override
    public GCommodity selectGCommodityById(Long id) {
        return gCommodityMapper.selectGCommodityById(id);
    }

    @Override
    public GCommodityVo selectGCommodityVoById(Long id) {
        return gCommodityMapper.selectGCommodityVoById(id);
    }

    /**
     * 查询商品列表
     *
     * @param req 商品
     * @return 商品
     */
    @Override
    public List<GCommodityVo> selectGCommodityList(GCommodityListReq req) {
        req.setLike(JpaUtil.getNullOrLikeStr(req.getLike()));
        req.setName(JpaUtil.getNullOrLikeStr(req.getName()));

        return gCommodityMapper.selectGCommodityList(req);
    }

    @Override
    public List<GCommodityVo> selectGCommodityListByPurchasingTypes(String purchasingTypes) {
        if (purchasingTypes.equals(GComConsts.purchasing_types_year)) {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            // 用户是否租用两年
            if (!user.isRentYear())
                return new ArrayList<>();
        }
        return gCommodityMapper.selectGCommodityListByPurchasingTypes(purchasingTypes);
    }

    @Override
    public List<GCommodityVo> selectGCommodityListByType(String type) {
        return gCommodityMapper.selectGCommodityListByType(type);
    }

    /**
     * 新增商品
     *
     * @param req 商品
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertGCommodity(GCommodityAddReq req) {
        req.setId(null);
        if (StringUtils.isBlank(req.getCarouselUrl()))
            throw new CustomException("请上传商品图片");
        if (StringUtils.isBlank(req.getLitimgUrl())) throw new CustomException("请上传商品缩略图");
        if (StringUtils.isAnyBlank(req.getName(), req.getIntro(), req.getDetails()))
            throw new CustomException("请填写正确的商品信息");
        if (!sysDictDataService.existsDictLabel(DictTypeConsts.G_FACILITY_TYPE, req.getFacilityType()))
            throw new CustomException("请选择正确的商品分类");
        if (req.getFacilityType().equals(GComConsts.FACILITY_TYPE_OFFICE))
            req.setPurchasingTypes(GComConsts.purchasing_types_buy);
        else if (!sysDictDataService.existsDictLabel(DictTypeConsts.G_PURCHASING_TYPES, req.getPurchasingTypes()))
            throw new CustomException("请选择正确的商品类型");
        if (!gCommodityTypeService.existsByIdAndType(req.getFacilityDetailsType(), req.getFacilityType()))
            throw new CustomException("请选择正确的商品详细分类");
        if (req.getCashPledge() == null)
            req.setCashPledge(0.0);
        if (req.getCashPledge() < 0)
            throw new CustomException("请输入正确的押金金额");
        if (req.getCount() == null || req.getCount() < 1)
            throw new CustomException("请输入正确的数量");
        List<GCommodityModelAddReq> modelList = req.getModelList();
        if (req.getIsModel()) {
            if (modelList == null || modelList.size() < 1)
                throw new CustomException("选择多规格时请添加规格");
        } else if (req.getPrice() == null || req.getPrice() <= 0)
            throw new CustomException("请输入正确的金额");
        GCommodity gCommodity = new GCommodity();
        ToolUtils.copyPropertiesIgnoreNull(req, gCommodity);
//        gCommodity.setCarouselUrl(cn.scw.common.utils.StringUtils.listToString(req.getCarouselUrl()));

        int resRow = gCommodityMapper.insertGCommodity(gCommodity);
        if (resRow < 1)
            throw new CustomException("商品添加失败");
        if (req.getIsModel()) {
            for (GCommodityModelAddReq modelReq : modelList) {
                if (StringUtils.isBlank(modelReq.getName()))
                    throw new CustomException("请输入规格");
                if (modelReq.getPrice() <= 0)
                    throw new CustomException("请输入正确的规格价格");
                GCommodityModel gCommodityModel = new GCommodityModel(modelReq);
                gCommodityModel.setCommodityId(gCommodity.getId());
                int i = gCommodityModelService.insertGCommodityModel(gCommodityModel);
                if (i < 1)
                    throw new CustomException("商品规格添加失败");
            }
        }
        return 1;
    }

    /**
     * 修改商品
     *
     * @param req 商品
     * @return 结果
     */
    @Override
    public int updateGCommodity(GCommodityAddReq req) {
        GCommodity gCommodity = gCommodityMapper.selectGCommodityById(req.getId());
        if (gCommodity == null)
            throw new CustomException("商品不存在~");
//        if (req.getCarouselUrl() != null && req.getCarouselUrl().size() > 0) {
//            gCommodity.setCarouselUrl(cn.scw.common.utils.StringUtils.listToString(req.getCarouselUrl()));
//            req.setCarouselUrl(null);
//        }

        if (StringUtils.isNotBlank(req.getPurchasingTypes()) && !req.getPurchasingTypes().equals(gCommodity.getPurchasingTypes())) {
            if (!sysDictDataService.existsDictLabel(DictTypeConsts.G_PURCHASING_TYPES, req.getPurchasingTypes()))
                throw new CustomException("请选择正确的商品类型");
        }
        if (StringUtils.isNotBlank(req.getFacilityType()) && !req.getFacilityType().equals(gCommodity.getFacilityType())) {
            if (!sysDictDataService.existsDictLabel(DictTypeConsts.G_FACILITY_TYPE, req.getFacilityType()))
                throw new CustomException("请选择正确的商品分类");
        }
        if (req.getFacilityDetailsType() != null && !req.getFacilityDetailsType().equals(gCommodity.getFacilityDetailsType())) {
            if (!gCommodityTypeService.existsByIdAndType(req.getFacilityDetailsType(), req.getFacilityType()))
                throw new CustomException("请选择正确的商品详细分类");
        }
        if (gCommodity.getCashPledge() != null) {
            if (!gCommodity.getCashPledge().equals(req.getCashPledge()) && (req.getCashPledge() < 0 /*|| req.getPrice() <= 0*/)) {
                throw new CustomException("请选择正确的金额");
            }
        }
        if (gCommodity.getCount() != req.getCount() && req.getCount() < 1) {
            throw new CustomException("请输入正确的数量");
        }

        if (req.getIsModel()) {
            if (req.getDelModelList() != null && req.getDelModelList().length > 0) {
                gCommodityModelService.deleteGCommodityModelByIds(req.getDelModelList());
            }
            List<GCommodityModelAddReq> modelList = req.getModelList();

            if (modelList != null && modelList.size() > 0) {
                for (GCommodityModelAddReq modelReq : modelList) {
                    if (modelReq.getId() != null) {
                        GCommodityModel model = gCommodityModelService.selectGCommodityModelById(modelReq.getId());
                        if (StringUtils.isNotBlank(modelReq.getName()) && !modelReq.getName().equals(model.getName())) {
                            boolean exists = gCommodityModelService.existsByCommodityIdAndName(gCommodity.getId(), modelReq.getName());
                            if (exists)
                                throw new CustomException("商品规格已存在");
                            model.setName(modelReq.getName());
                        }
                        if (modelReq.getPrice() <= 0)
                            throw new CustomException("请输入正确的规格价格");
                        model.setPrice(modelReq.getPrice());
                        gCommodityModelService.updateGCommodityModel(model);
                    } else {
                        if (StringUtils.isBlank(modelReq.getName()))
                            throw new CustomException("请输入规格");
                        if (modelReq.getPrice() <= 0)
                            throw new CustomException("请输入正确的规格价格");
                        GCommodityModel gCommodityModel = new GCommodityModel(modelReq);
                        gCommodityModel.setCommodityId(gCommodity.getId());
                        int i = gCommodityModelService.insertGCommodityModel(gCommodityModel);
                        if (i < 1)
                            throw new CustomException("商品规格添加失败");
                    }
                }
            } else
                throw new CustomException("选择多规格时请添加规格");
        }
        ToolUtils.copyPropertiesIgnoreNull(req, gCommodity);

        return gCommodityMapper.updateGCommodity(gCommodity);
    }

    @Override
    public int updateGCommodity(GCommodity gCommodity) {
        return gCommodityMapper.updateGCommodity(gCommodity);
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品ID
     * @return 结果
     */
    @Override
    public int deleteGCommodityByIds(Long[] ids) {
        return gCommodityMapper.deleteGCommodityByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品ID
     * @return 结果
     */
    @Override
    public int deleteGCommodityById(Long id) {
        return gCommodityMapper.deleteGCommodityById(id);
    }
}
